package com.game.app.service.impl;

import org.json.JSONObject;
import org.springframework.stereotype.Service;

import com.game.app.model.UserModel;
import com.game.app.service.WeChatService;
import com.game.app.util.HttpUtil;
import com.game.app.util.PropertiesUtil;

@Service
public class WeChatServiceImpl implements WeChatService {

	static String WECHAT_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=SECRET&js_code=%s&grant_type=authorization_code";

	@Override
	public String loginGetUid() {

		// 登陆微信获取微信的openid以及sessionkey
		String loginUrl = String.format(WECHAT_LOGIN_URL, PropertiesUtil.getString("appid"),
				PropertiesUtil.getString("secret"));
		String responseConString = HttpUtil.get(loginUrl);
		JSONObject jsonWeChatLoginObj = new JSONObject(responseConString);
		int errcode = jsonWeChatLoginObj.getInt("errcode");
		String openIdString = jsonWeChatLoginObj.getString("openid");
		String sessionKeyString = jsonWeChatLoginObj.getString("session_key");
		// 将获取到的用户信息openid sessionkey 写入数据库

		if (errcode == 0) {
			UserModel model = new UserModel();
			model.setOpenId(openIdString);
			model.setSessionkey(sessionKeyString);
			return openIdString;
		}
		return "";

	}
}
